// #ifdef MP-WEIXIN
import { useTabbarStore } from "@/store/tabbar";
import { useStorageStore } from "@/store/storage";
const tabbarStore = useTabbarStore();
const storageStore = useStorageStore();
// #endif
import { getToken, getUserInfo } from "@/util/auth";
export const getImageUrl = (suffix, prefix = import.meta.env.VITE_IMAGE_BASE_URL) => {
    return `${prefix}/${suffix}`;
};


// 点击更多
export const moreClick = async ({ type, pageMap = {}, params = {} } = {}) => {
    if (!type) return;
    if (!pageMap[type]) return;
    // 参数化统一
    let ops = {};
    if (typeof pageMap[type] === "string") {
        ops = {
            url: pageMap[type],
            params: params || {},
        }
    } else {
        ops = {
            url: pageMap[type].path,
            params: params || {},
            isTabbar: pageMap[type].isTabbar || false,
            tabbarIndex: pageMap[type].tabbarIndex,
        };
    }

    if (ops.isTabbar) {
        // #ifdef MP-WEIXIN
        tabbarStore.setCurrentTab(ops.tabbarIndex);
        // #endif
        uni.switchTab({ url: ops.url, params: ops.params });
    } else {
        uni.$u.route({ url: ops.url, params: ops.params });
    }
};


export const sleep = (ms) => {
    return new Promise(resolve => setTimeout(resolve, ms));
};

// 获取当前小程序信息
export const getCurrentMiniProgramInfo = () => {
    try {
        const accountInfo = uni.getAccountInfoSync();
        return accountInfo;
    } catch (e) {
        return {};
    }
};


export const getLoginCode = async () => {
    try {
        const res = await uni.login({ provider: "weixin" });
        return res.code;
    } catch (e) {
        return "";
    }
};

// 上传文件到OSS
export const uploadFileToOss = async (tempFilePath, token) => {
    try {
        const config = {
            header: {
                "content-type": "multipart/form-data",
                "Authorization": "Bearer " + (token || storageStore.storage.loginInfo.access_token),
                clientid: import.meta.env.VITE_CLIENT_ID,
            }
        };
        const uploadUrl = import.meta.env.VITE_BASE_URL + import.meta.env.VITE_OSS_UPLOAD_URL;
        return new Promise((resolve, reject) => {
            uni.uploadFile({
                url: uploadUrl,
                filePath: tempFilePath,
                name: 'file',
                header: config.header,
                success: (res) => {
                    resolve(JSON.parse(res.data).data);
                },
                fail: (err) => {
                    reject(err);
                }
            });
        });
    } catch (err) {
        return Promise.reject(err);
    }
}

// 同步方式读取所有缓存
export const getAllStorage = () => {
    try {
        const storageInfo = uni.getStorageInfoSync();
        const allData = {};
        storageInfo.keys.forEach(key => {
            try {
                const value = uni.getStorageSync(key);
                allData[key] = value;
            } catch (e) {
                console.error(`读取缓存键 ${key} 失败:`, e);
            }
        });
        return allData;
    } catch (e) {
        console.error('获取缓存信息失败:', e);
        return null;
    }
};

// 获取picker中的label
export const getPickerLabel = ({ valueKey, value, list, textKey = "text", emptyText = "请选择" }) => {
    if (!value) return emptyText;
    const findItem = list.find(item => item[valueKey] === value);
    return findItem[textKey];
}

// 获取下拉框中的label
export const getLabel = ({ valueKey = 'value', labelKey = 'label', value, list, emptyText = '暂无' }) => {
    if (value == null || value === '') return emptyText;
    let text = '';
    let valueArr = value.toString().split(',');
    let findArr = list.filter((item) => {
        return valueArr.includes(item[valueKey].toString());
    });
    if (findArr.length > 0) {
        text = findArr.map((item) => item[labelKey]).join(',');
    }
    return text || emptyText;
};

export const getSplitImage = (images) => {
    if (!images) return [];
    return images.split(',');
}

// 保存图片到相册
export const saveImageToAlbum = async (url) => {
    try {
        // 先下载图片到本地临时路径
        const downloadRes = await new Promise((resolve, reject) => {
            uni.downloadFile({
                url: url,
                success: (res) => {
                    if (res.statusCode === 200) {
                        resolve(res);
                    } else {
                        reject(new Error('下载失败'));
                    }
                },
                fail: (err) => {
                    reject(err);
                }
            });
        });

        // 保存图片到相册
        const saveRes = await new Promise((resolve, reject) => {
            uni.saveImageToPhotosAlbum({
                filePath: downloadRes.tempFilePath,
                success: () => {
                    resolve({ success: true });
                },
                fail: (err) => {
                    reject(err);
                }
            });
        });

        return saveRes;
    } catch (error) {
        console.error('保存图片失败:', error);
        throw error;
    }
};

// 预览图片（增强版，支持长按保存）
export const previewImageUtil = (url, urls, index) => {
    const currentIndex = index !== undefined ? index : urls.indexOf(url);

    // 使用增强的预览功能
    uni.previewImage({
        current: currentIndex,
        urls: urls,
        longPressActions: {
            itemList: ['保存到手机相册'],
            success: function (data) {
                const { current } = data;
                const currentUrl = urls[current];

                // 保存图片到相册
                saveImageToAlbum(currentUrl).then(() => {
                    uni.showToast({
                        title: '图片已保存到相册',
                        icon: 'success'
                    });
                }).catch((err) => {
                    if (err.errMsg && err.errMsg.includes('auth deny')) {
                        uni.showModal({
                            title: '提示',
                            content: '需要您授权保存图片到相册，请在设置中开启相册权限',
                            confirmText: '去设置',
                            success: (res) => {
                                if (res.confirm) {
                                    uni.openSetting();
                                }
                            }
                        });
                    } else {
                        uni.showToast({
                            title: '保存失败，请重试',
                            icon: 'none'
                        });
                    }
                });
            },
            fail: function (err) {
                console.error('长按操作失败:', err);
            }
        }
    });
};

// 简化版预览图片（保持向后兼容）
export const previewImageSimple = (url, urls) => {
    const currentIndex = urls.indexOf(url);
    uni.previewImage({
        current: currentIndex,
        urls: urls,
    });
}


// 拨打电话
export const makePhoneCall = async ({ tel, success, fail, showToast = false }) => {
    if (!tel) return;
    try {
        await uni.makePhoneCall({ phoneNumber: tel })
        success && success();
    } catch (error) {
        showToast && uni.$u.toast("拨打电话失败");
        fail && fail(error);
    }
}



// 文字复制
export const copyText = (text, showToast = true) => {
    return new Promise((resolve, reject) => {
        uni.setClipboardData({
            data: text, showToast,
            success: () => {
                resolve();
            },
            fail: () => {
                reject();
            }
        });
    });
}

